package eu.irreality.dai.ui.keyboard;

import java.awt.event.KeyEvent;
import java.lang.reflect.Constructor;

import eu.irreality.dai.gameplay.controller.actions.ControllerAction;
import eu.irreality.dai.gameplay.controller.actions.ControllerActionProcessor;
import eu.irreality.dai.gameplay.entities.AliveEntity;
import eu.irreality.dai.gameplay.states.GameState;
import eu.irreality.dai.gameplay.states.MainState;
import eu.irreality.dai.gameplay.world.GameWorld;

public class KeyProcessor
{

    private GameWorld world;

    private GameState currentState;

    public KeyProcessor(GameWorld world)
    {
	this.world = world;
	currentState = MainState.getInstance();
    }

    // public boolean isListening(KeyEvent e)
    // {
    // if (isGameListening())
    // {
    // return InputManager.getInstance().isMapped(e);
    // }
    // return false;
    // }

    public void keyPressed(KeyEvent e)
    {
	/*
	 * System.out.println(new KeyDescriptor(e));
	 * System.out.println(e.getKeyChar());
	 * System.out.println((int)e.getKeyChar());
	 */
	Class<ControllerAction> classAction = InputManager.getInstance()
		.getKeyAction(new KeyDescriptor(e), this.getCurrentState());
	if (classAction != null)
	{
	    processAction(classAction);
	    e.consume();
	}
    }

    public void processAction(Class<ControllerAction> classAction)
    {
	try
	{
	    Constructor<ControllerAction> cons = classAction.getConstructor(
		    KeyProcessor.class, GameWorld.class, AliveEntity.class);
	    ControllerAction action = cons.newInstance(this, world, world
		    .getPlayerCharacter());
	    ControllerActionProcessor.process(action);
	} catch (Exception e)
	{
	    e.printStackTrace();
	}

    }

    public boolean isGameListening()
    {
	// return game.isRunning() && !game.isPaused();
	return true;
    }

    public GameState getCurrentState()
    {
	return currentState;
    }

    public void setState(GameState gs)
    {
	currentState = gs;
    }

}
